package com.zhu.androidsample.util;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZCP on 2015/11/19.
 * mail:43426073@qq.com
 */
public class JsonBeanUtil {

    public static final String TAG = "DEBUG";
    static Gson gson = new Gson();

    public static String bean2Json(Object bean) {
        return gson.toJson(bean);
    }


    public static Object json2Bean(JSONObject json, Class<?> clazz) {
        Log.d(TAG, "json2Bean() called with: " + "json = [" + json + "], clazz = [" + clazz + "]");
        return gson.fromJson(json.toString(), clazz);
    }


    public static Object json2Bean(String json, Class<?> clazz) {
        return gson.fromJson(json, clazz);
    }

    public static Object json2Bean(String json, Type type) {
        return gson.fromJson(json, type);
    }

    public static List<Object> json2BeanList(JSONArray array, Class<?> clazz)
            throws JSONException {
        List<Object> result = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject jsonObj = array.optJSONObject(i);
            Object bean = gson.fromJson(jsonObj.toString(), clazz);
            result.add(bean);
        }
        return result;
    }
    public static List<Object> json2BeanList(String json,Class<?> clazz){
        Type type =  new TypeToken<ArrayList<?>>(){}.getType();
        return gson.fromJson(json,type);
    }
}
